auto.waitFor()

var storage = storages.create("xiangxiangyuedu");
var time = random(2000, 3000)

function launchAppEnhance(app_name) {
  let thread = threads.start(function () {
    toastLog("检查是否有打开权限!")
    while (true) {
      var allow = text("允许").findOne(5000)
      if (allow) {
        sleep(1000)
        toastLog("发现允许授权!")
        allow.click()
        sleep(1000)
        thread.interrupt()
        break
      }
    }
  })
  sleep(1000)
  var result = launchApp(app_name)
  sleep(3000)
  thread.interrupt()
  return result
}

// 点击控件坐标，控件的clickbale为false的时候
function 点击控件(x) {
  var weight = x.bounds()
  click(weight.centerX(), weight.centerY())
}

function login() {
  sleep(5000)
  var index = 0
  while (index < 5) {
    var 每日收听 = text('每日收听').findOne(2000)
    if (每日收听) {
      toastLog('已经在登录状态')
      break
    }
    var 登录 = id('com.my.transactionbar:id/submit_button').findOne(2000)
    if (登录) {
      点击控件(登录)
      sleep(time)
      break
    }
    index++
  }
}

function task() {
  var 兑换商店 = text('兑换商店').findOne(5000)
  if (兑换商店) {
    sleep(time)
    兑换商店.click()
    sleep(time)
    var 我的技能包 = text('我的技能包').findOne(3000)
    if (我的技能包) {
      我的技能包.click()
      sleep(time)
      var 每日任务 = textStartsWith('每日任务:').findOne(5000)
      if (每日任务) {
        var num = parseFloat(每日任务.text().slice(5, 6))
        if (num == 5) {
          toastLog('已经完成收听')
          sleep(time)
        } else {
          back()
          var video_button = id('com.my.transactionbar:id/video_switch_button').findOne(5000)
          if (video_button) {
            sleep(time)
            video_button.click()
            sleep(time)
            var 倒计时 = id('com.my.transactionbar:id/count_down_text_view').findOne(3000)
            if (倒计时) {
              var 分 = parseFloat(倒计时.text().slice(0, 2))
              var 秒 = parseFloat(倒计时.text().slice(3, 5))
              toastLog('等待' + 分 + '分' + 秒 + '秒')
              sleep((分 * 60 + 秒) * 1000)
              sleep(4000)
            }
            var 领取 = text('领取').findOne(5000)
            if (领取) {
              领取.click()
              sleep(time)
            }
          }
        }
      }
    }
  }
}

function main() {
  let open_app = launchAppEnhance("交易吧");
  if (open_app) {
    var thread_1 = threads.start(function () {
      toastLog("检查广告弹窗")
      while (true) {
        var widget = id('com.my.transactionbar:id/cancel_button').findOne(2000)
        if (widget) {
          widget.click()
        }
      }
    })
    login()
    task()
    thread_1.interrupt()
  }
  else {
    toastLog("交易吧打开失败，请确认是否安装并授权打开!");
  }
}


try {
  main();
} catch (error) {
  toastLog(error);
}

storage.put("script_running_status", "end");